<template>
  <div class="header-container flex self-start align-items-center border-box">
    <div class="left flex justify-content-center align-items-center">
      <el-button :icon="ArrowLeft" circle @click="router.push('/my-quiz')" />
    </div>

    <div class="center flex align-items-center space-between pl-15 pr-15">
      <div>
        <el-button type="success" size="small" @click="handleSave">保存问卷</el-button>
        <el-button type="danger" size="small" v-if="!route.params.id" @click="handleReset">
          重置问卷
        </el-button>
      </div>
      <div v-if="route.params.id" style="transform: translateX(80px)">
        问卷标题：<el-input style="width: 600px" v-model="editTitle" @blur="handleEditTitle" />
      </div>
      <div>
        <el-text class="mx-1 mr-20">题目数量：{{ store.surveyCount }}</el-text>
        <el-button type="primary" size="small" v-if="route.params.id" @click="handlePreview">
          预览问卷
        </el-button>
      </div>
    </div>

    <div class="right flex justify-content-center align-items-center">
      <DarkSwitch />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import DarkSwitch from '@/components/Common/DarkSwitch.vue';
import { useEditorStore } from '@/stores/useEditor';
import { updateSurveyTitleById } from '@/db/operation';

const props = defineProps(['title']);
const route = useRoute();
const router = useRouter();
const store = useEditorStore();
const editTitle = ref('');

watch(
  () => props.title,
  () => {
    editTitle.value = props.title;
  },
  { immediate: true },
);

function handleReset() {
  ElMessageBox.confirm('是否确定重置试卷？已有题目将全部删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      store.resetComs();
      ElMessage.success('重置成功');
    })
    .catch(() => {
      ElMessage.info('已取消重置');
    });
}

function handleSave() {
  // 根据路由id判断是新增还是编辑
  if (route.params.id) {
    store
      .updateComs(+route.params.id, {
        updateDate: new Date().getTime(),
        surveyCount: store.surveyCount,
        coms: JSON.parse(JSON.stringify(store.coms)),
      })
      .then(() => {
        ElMessage.success('保存成功');
      })
      .catch(() => {
        ElMessage.error('保存失败');
      });
  } else {
    ElMessageBox.prompt('请输入问卷的标题', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    })
      .then(({ value }) => {
        const surveyToSave = {
          createDate: new Date().getTime(),
          updateDate: new Date().getTime(),
          title: value,
          surveyCount: store.surveyCount,
          coms: JSON.parse(JSON.stringify(store.coms)),
        };
        store
          .saveComs(surveyToSave)
          .then(() => {
            ElMessage.success('保存成功');
            router.push('/my-quiz');
          })
          .catch(() => {
            ElMessage.error('保存失败');
          });
      })
      .catch(() => {
        ElMessage.info('已取消保存');
      });
  }
}

function handleEditTitle() {
  updateSurveyTitleById(+route.params.id, editTitle.value)
    .then(() => {
      ElMessage.success('标题修改成功');
    })
    .catch(() => {
      ElMessage.error('标题修改失败');
    });
}

function handlePreview() {
  ElMessageBox.confirm('预览会保存问卷，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleSave();
      router.push(`/preview/${route.params.id}`);
    })
    .catch(() => {
      ElMessage.info('取消预览');
    });
}
</script>

<style lang="scss" scoped>
.header-container {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid var(--el-menu-border-color);
  background-color: var(--el-bg-color);
  position: fixed;
  z-index: 10;
  top: 0;
  .left {
    width: 60px;
    height: 100%;
  }
  .center {
    flex: 1;
    height: 100%;
    border-left: 1px solid var(--el-menu-border-color);
    border-right: 1px solid var(--el-menu-border-color);
  }
  .right {
    padding-top: 5px;
    width: 120px;
    height: 100%;
  }
}
</style>
